import { judgeDataType } from '@utils/methods'

/**
 * 已存在的缓存
 * systemInfo 账户信息
 * token
 * isCollapse 左侧菜单收缩展开
 * menuList 菜单列表
 * */
type StorageKey = 'systemInfo' | 'token' | 'isCollapse' | 'menuList'

interface StorageType {
    /** @description 存入 */
    set: (key: string, value: any) => void
    /** @description 取出 */
    get: (key: StorageKey) => any
    /** @description 删除 */
    remove: (key: StorageKey) => void
    /** @description 更新 */
    update: (key: StorageKey, newVal: any) => void
    /** @description 清除 */
    clear: () => void
}

/**
 * 缓存操作
 * */
const Storage: StorageType = {
    set(key, value) {
        localStorage.setItem(key, JSON.stringify(value))
    },
    get(key) {
        const result = localStorage.getItem(key)
        return result ? JSON.parse(result) : undefined
    },
    update(key, value) {
        let result = value
        if (judgeDataType(value) === 'object') {
            result = { ...this.get(key), ...value }
        }
        if (judgeDataType(value) === 'array') {
            result = [...this.get(key), ...value]
        }
        this.set(key, result)
    },
    remove(key) {
        localStorage.removeItem(key)
    },
    clear() {
        localStorage.clear()
    }
}

export default Storage
